<template>
  <el-cascader v-model="list" placeholder="请选择行政区划" :props="props1" clearable separator=","
               collapse-tags collapse-tags-tooltip @change="getCheckedArea" ref="checkedAreaRef"
               :options="optionsSelect">
  </el-cascader>
</template>
<script setup>
import { getProvince, getChildArea } from "@/api/system/division"

const { proxy } = getCurrentInstance()
const props = defineProps(['divisionNames','provinceId','cityId','countyId']);
const emits = defineEmits(['getAreaSelect'])

const data = reactive({
  list:[],
  optionsSelect: [],
})
const { list,optionsSelect } = toRefs(data)

//行政区划选择
const checkedAreaRef = ref();
const props1 = {
  multiple: true
};

// 处理数据
function disposeata(data) {
  data.forEach((item) => {
    item.value = item.name;
    item.label = item.name;
    item.key = item.id;
    item.children && disposeata(item.children);
  });
  return data;
}
//查询行政区划列表
function getTreeselect() {
  console.log("查询行政区划列表：");
  let treeList = [];
  let provinceArray = provinceData.value;
  for (let i = 0; i < provinceArray.length; i++) {
    let provinceId = provinceArray[i].id;
    let children = [];
    let cityArray = allCityData.value.get(provinceId);
    if(cityArray){
      for (let j = 0; j < cityArray.length; j++) {
        let cityId = cityArray[j].id;
        let subChildren = [];
        let countyData = allCountyData.value.get(cityId);
        if(countyData){
          for (let k = 0; k < countyData.length; k++) {
            let countyObj = {
              id:countyData[k].id,
              name:countyData[k].name,
              children:[]
            };
            subChildren.push(countyObj);
          }
        }
        let cityObj = {
          id:cityId,
          name:cityArray[j].name,
          children:subChildren
        };
        children.push(cityObj);
      }
    }
    let obj = {
      id:provinceId,
      name:provinceArray[i].name,
      children:children
    }
    treeList.push(obj);
  }
  console.log("行政区划列表");
  console.log(treeList);

  optionsSelect.value = disposeata(treeList);
  // 'provinceId','cityId','countyId'
  let province = optionsSelect.value.find(item => item.id == props.provinceId)
  let city
  if(props.cityId != '') {
    city = province.children.find(item => item.id == props.cityId)
    province.children = [city]
  }
  if(props.countyId != '') {
    let county = province.children[0].children.find(item => item.id == props.countyId)
    city.children = [county]
  }
  optionsSelect.value = [province]
  console.log("行政区划列表optionsSelect");
  console.log(optionsSelect.value);
}

const provinceData = ref([]); //全部省
const allCityData = ref(new Map()); //全部市
const allCountyData = ref(new Map()); //全部区县
/** 获取省列表 */
function getProvinceData() {
  provinceData.value = [];
  allCityData.value = new Map();
  allCountyData.value = new Map();
  //全部省
  getProvince().then((response) => {
    let provinceArray = response.data;
    provinceData.value = provinceArray;
    for (let i = 0; i < provinceArray.length; i++) {
      let provinceId = provinceArray[i].id;
      //获取市列表
      getCityData(provinceId);
    }
  });
}

//获取市列表
function getCityData(provinceId) {
  getChildArea(provinceId).then(response => {
    let cityArray = response.data;
    allCityData.value.set(provinceId, cityArray);
    for (let i = 0; i < cityArray.length; i++) {
      //获取区县列表
      getCountyData(cityArray[i].id);
    }
  });
}

//获取区县列表
function getCountyData(cityId) {
  getChildArea(cityId).then(response => {
    let countyData = response.data;
    allCountyData.value.set(cityId, countyData);
  });
}

//选择行政区划
function getCheckedArea() {
  console.log("选择行政区划");
  console.log(checkedAreaRef.value);
  let taskDistrict = checkedAreaRef.value.getCheckedNodes();
  taskDistrict = taskDistrict.filter(option => !(option.parent && option.parent.checked))
  console.log(taskDistrict, "选中值");
  let parentdistrictList = taskDistrict.map((item, index) => {
    return item.pathLabels.join("-");
  });
  console.log(parentdistrictList);
  // let arr = JSON.parse(JSON.stringify(parentdistrictList));
  // console.log(arr);
  /*let bouas = taskDistrict.map((item, index) => {
    console.log(item);
    let pathNodes = item.pathNodes;
    let id = pathNodes[0].data.id;
    let provinceId = pathNodes[0].data.id;
    let provinceName = pathNodes[0].data.name;
    let cityId = null;
    let cityName = null;
    if(pathNodes.length>1){
      cityId = pathNodes[1].data.id;
      cityName = pathNodes[1].data.name;
      id = cityId;
    }
    let countyId = null;
    let countyName = null;
    if(pathNodes.length>2){
      countyId = pathNodes[2].data.id;
      countyName = pathNodes[2].data.name;
      id = countyId;
    }
    //行政区划
    let obj = {
      id:id,
      provinceId:provinceId,
      cityId:cityId,
      countyId:countyId,
      provinceName:provinceName,
      cityName:cityName,
      countyName:countyName,
      qhId:null
    }
    return obj;
  });*/

  let divisionNameArray = taskDistrict.map((item, index) => {
    console.log(item);
    let nameText = "";
    let pathNodes = item.pathNodes;
    if(pathNodes.length==3){//区县
      let provinceName = pathNodes[0].data.name;
      let cityName = pathNodes[1].data.name;
      let countyName = pathNodes[2].data.name;
      nameText = provinceName + "-" + cityName + "-" + countyName;
    }else if(pathNodes.length==2){//市
      let countyChildren = pathNodes[1].children;
      for(let i=0;i<countyChildren.length;i++){
        if(countyChildren[i].text){
          if(nameText!=""){
            nameText += ",";
          }
          nameText += countyChildren[i].text.replaceAll(",","-");
        }
      }
    }else if(pathNodes.length==1){//省
      let cityChildren = pathNodes[0].children;
      for(let i=0;i<cityChildren.length;i++){
        let countyChildren = pathNodes[0].children[i].children;
        for(let j=0;j<countyChildren.length;j++){
          if(countyChildren[j].text){
            if(nameText!=""){
              nameText += ",";
            }
            nameText += countyChildren[j].text.replaceAll(",","-");
          }
        }
      }
    }
    console.log("nameText:"+nameText);
    return nameText;
  });
  let bouas = taskDistrict.map((item, index) => {
    console.log(item);
    let pathNodes = item.pathNodes;
    let id = pathNodes[0].data.id;
    let provinceId = pathNodes[0].data.id;
    let provinceName = pathNodes[0].data.name;
    let cityId = null;
    let cityName = null;
    if(pathNodes.length>1){
      cityId = pathNodes[1].data.id;
      cityName = pathNodes[1].data.name;
      id = cityId;
    }
    let countyId = null;
    let countyName = null;
    if(pathNodes.length>2){
      countyId = pathNodes[2].data.id;
      countyName = pathNodes[2].data.name;
      id = countyId;
    }
    //行政区划
    let obj = {
      id:id,
      provinceId:provinceId,
      cityId:cityId,
      countyId:countyId,
      provinceName:provinceName,
      cityName:cityName,
      countyName:countyName,
      qhId:null
    }
    return obj;
  });
  let divisionNames = divisionNameArray.join(",");
  emits("getAreaSelect",{divisionNames:divisionNames,list:parentdistrictList,bouas:bouas});
}

//获取默认选择行政区划
const getDivisionNames = watch(() => props.divisionNames, value => {// watch函数监听props.divisionNames
  if(value){
    console.log("获取默认选择行政区划");
    console.log(value);
    let divisionNamesList = [];
    let array = value.split(",");
    for(let i=0;i<array.length;i++){
      divisionNamesList.push(array[i].split("-"));
    }
    list.value = divisionNamesList;
    console.log(list.value);
  }
},{immediate:true});

onMounted(() => {
  //查询省列表
  getProvinceData();
  setTimeout(function (){
    //查询行政区划列表
    getTreeselect();
  },2000);
})

</script>
<style scoped></style>